<?php

namespace App\Http\Services;

use App\Http\Helpers\Crypter;
use App\Http\Helpers\Http;
use App\Http\Helpers\Sms;
use App\Http\Helpers\Sign;
use App\Models\Admin;
use App\Models\Role;
use App\Models\LoginRecord;
use GeoIp2\Database\Reader;

class LoginService{

    public static function getAdd($user){
        $userId = $user['name']."(".$user['card_number'].")"."[".$user['school']['name']."]"."|".$user['school']['code'];
        $crypter = new Crypter();
        $data = [
            'userid' => $userId,
            'ip' => Sign::getClientIp(),
//            'hardware' => Sign::getPhoneModel(),
            'os' => php_uname('s').php_uname('r'),
            't' => time()
        ];
        $decrypt = [
            'color' => "08c27c"
        ];
        $url = $crypter::getAuthorizedUrl(BASE_PC_SUBMIT, $data, $decrypt);
        return $url;
    }

    public static function getlist($user){
        $userId = $user['name']."(".$user['card_number'].")"."[".$user['school']['name']."]"."|".$user['school']['code'];

        $crypter = new Crypter();
        $data = [
            'userid' => $userId,
            'ip' => Sign::getClientIp(),
//            'hardware' => Sign::getPhoneModel(),
            'os' => php_uname('s').php_uname('r'),
            't' => time()
        ];
        $decrypt = [
            'color' => "08c27c"
        ];
        $url = $crypter::getAuthorizedUrl(BASE_PC_FEEDBACK, $data, $decrypt);
        return $url;
    }

    /**
     *移动端用户缓存
     * @author: lican<364548233@qq.com>
     */
    public static function setUser($admin){ //'stu_id', 'card_number', 'name', 'ocode', 'telephone', 'email'
        $key = PREFIX_MOBILE . '_auth';
        $data = [
            'id' => $admin['stu_id'],
            'name' => $admin['name'],
            'time' => time()
        ];
        $encrypt = encrypt($data);
        $expire = time() + 86400;
        setcookie($key, $encrypt, $expire, '/');
        $key = $key . $data['id'];
        app('redis')->setex($key, 86400, json_encode($admin));
        return true;
    }

    /**
     *获取移动端用户信息
     * @author: lican<364548233@qq.com>
     */
    public static function getUser(){
        $key = PREFIX_MOBILE . '_auth';
        if(isset($_COOKIE[$key]) && !empty($_COOKIE[$key])){
            $encrypt = $_COOKIE[$key];
        }else{
            return [];
        }
        try{
            $data = decrypt($encrypt);
        }catch(\Exception $e){
            Sign::writeLog(__FUNCTION__, $e->getMessage(), 'login');
            return [];
        }
        $key = $key . $data['id'];
        $user = app('redis')->get($key);
        return json_decode($user, true);
    }

    /**
     *微校移动端登录
     * @author: lican<364548233@qq.com>
     */
    public static function mobileLogin($wxcode, $schoolCode){
        if(!empty($wxcode)){
            try{
                $school = SchoolService::getSchoolInfo($schoolCode);
                $accessToken = ApiService::getOauthToken($wxcode, $school, AuthService::H5_REDIRECT);
                $user = ApiService::getUserInfo($accessToken, $school); //获取到移动端用户信息
                LoginService::setUser($user); //'stu_id', 'card_number', 'name', 'ocode', 'telephone', 'email'
            }catch(\Exception $e){
                Sign::writeLog('获取用户信息时报： ', $e->getMessage(), 'login');
            }
            if(empty($user)){
                $user = LoginService::getUser();
            }
        }else{
            $user = LoginService::getUser();
        }

        if(empty($user) && empty($schoolCode)){
            return MsgService::getMsg(1001);
        }else if(empty($user) && (isset($schoolCode))){
            $redirectUri = AuthService::getUserH5AuthUri($schoolCode, ApiService::APP_KEY);
            header("location:{$redirectUri}");
//            return MsgService::getMsg(4001, ['redirect_uri' => $redirectUri]);
        }
        return MsgService::getMsg(0, $user);
    }

    /**
     *微校PC登录
     * @author lican<364548233@qq.com>
     */
    public static function weixiaoLogin($wxcode, $schoolCode){
        if(!empty($wxcode)){
            $school = SchoolService::getSchoolInfo($schoolCode);
//            $accessToken = ApiService::getOauthToken($wxcode, $school, AuthService::PC_REDIRECT);
            $accessToken = ApiService::getOldAuthToken();
            if($accessToken){
//                $admin = ApiService::getUserInfo($accessToken, $school);
                $admin = ApiService::getOldUserInfo($wxcode, $accessToken, $school);
               if($admin){
                   $res = Admin::where('name', $admin['name'])
                       ->where('stu_id', $admin['stu_id'])
                       ->first();

                   $role = ApiService::getManageRule($schoolCode, $admin['card_number']); //获取管理员权限组

                   if(empty($res)){
                       $res = new Admin();
                       $salt = str_random(8);
                       $res->password = md5($admin['card_number']. $salt);
                       $res->salt = $salt;
                       $res->status = Role::STATUSON;
                   }
                   $res->name = $admin['name'];
                   $res->role_id = $role;
                   $res->email = isset($admin['email']) ? $admin['email'] : '';
                   $res->mobile = isset($admin['mobile']) ? $admin['mobile'] : '';
                   $res->ip = Sign::getClientIp();
                   $res->stu_id = $admin['stu_id'];
                   $res->save();
                   $res = $res->toArray();
                   $res['school_code'] = isset($admin['ocode']) ? $admin['ocode'] : '';
                   $res['card_number'] = $admin['card_number'];
                   $admin = $res;
                   $admin['school'] = $school;
                   LoginService::setAdmin($admin);
               }else{
                   $admin = self::getAdmin();
               }

            }else{
                $admin = self::getAdmin();
            }

        }else{
            $admin = self::getAdmin();
        }

//        if(empty($admin) && empty($schoolCode)){
//            return MsgService::getMsg(1001);
////        }else if(empty($admin) || (isset($schoolCode) && $schoolCode != $admin['school_code'])){
//        }else if(empty($admin) || (isset($schoolCode))){
//            $redirectUri = AuthService::getUserPcAuthUri($schoolCode, ApiService::APP_KEY);
//            header("location:{$redirectUri}");
////            return MsgService::getMsg(4001, ['redirect_uri' => $redirectUri]);
//        }

        LoginService::loginRecord($admin);
        return MsgService::getMsg(0, ['data' => $admin]);
    }


    /**
     *登录管理员信息存进cookie
     * @author lican<364548233@qq.com>
     */
    public static function setAdmin($admin){
        $data = [
            'id' => $admin['id'],
            'name' => $admin['name'],
            'login_time' => date('Y-m-d H:i:s')
        ];
        $encrypt  = encrypt($data);
        $expireAt = time() + 86400;

        $key = PREFIX . '_auth';
        setcookie($key, $encrypt, $expireAt, '/');
        $key = $key . $data['id'];
        app('redis')->setex($key, 86400, json_encode($admin));
        return true;
    }

    public static function getAdmin(){
        $key = PREFIX . '_auth';
        $encrypt = isset($_COOKIE[$key]) && !empty($_COOKIE[$key]) ? $_COOKIE[$key] : null;
        if(empty($encrypt)){
            return [];
        }
        try{
            $data = decrypt($encrypt);
        }catch(\Exception $e){
            Sign::writeLog(__FUNCTION__, $e->getMessage(), 'login');
            return [];
        }
        $key = $key . $data['id'];
        $admin = app('redis')->get($key);
        return json_decode($admin, true);
    }

    /**
     *记录管理员登录
     * @author lican<364548233@qq.com>
     */
    public static function loginRecord($admin, $type = null, $remark = '登录成功'){
        $loginRecord = new LoginRecord();
        $ip = Sign::getClientIp();
        $city = is_array(Sign::getCity($ip)) ? '未知' : Sign::getCity($ip);
        if($type === 0 || $type === 1){
            $remark = '异地登录成功';
        }
        $remark .= "，本次登录地为{$city}";
        $loginRecord->admin_id = $admin['id'];
        $loginRecord->name = $admin['name'];
        $loginRecord->ip = $ip;
        $loginRecord->remark = $remark;
        $loginRecord->save();
        Admin::where('id', $admin['id'])
            ->update(['ip' => $ip]);
    }

    public static function checkIp($admin){
        $loginRecord = LoginRecord::select('ip')
            ->where('admin_id', $admin['id'])
            ->orderBy('updated_at', 'desc')
            ->first();
        if($loginRecord){
            $lastIp = $loginRecord->ip;
            $newIp = Sign::getClientIp();
            $lastCity = Sign::getCity($lastIp);
            $newCity = Sign::getCity($newIp);
            if($lastCity != $newCity){
                return false;
            }
            return true;
        }
        return true;
    }

}
